#pragma once
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <functional>
#include <pthread.h>
#include "Thread.hpp"
#include "Log.hpp"

using namespace log_ns;

static const int gdefualtnum = 5;

template <class T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }
    void WakeUpAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool TQIsEmpty()
    {
        return _task_queue.empty();
    }
    void HandlerTask(std::string name)
    {
        while (true)
        {
            LockQueue();
            while (TQIsEmpty() && _isrunning)
            {
                _sleep_thread_num++;
                Sleep();
                _sleep_thread_num--;
            }
            if (TQIsEmpty() && !_isrunning)
            {
                // std::cout << name << " quit" << std::endl;
                LOG(DEBUG, "%s : quit\n", name.c_str());
                UnLockQueue();
                break;
            }
            T task = _task_queue.front();
            _task_queue.pop();
            // std::cout << name << ": " << task.result() << std::endl;
            //LOG(DEBUG, "hander task done, task is : %s\n", task.result().c_str());
            UnLockQueue();
            task();
        }
    }

    ThreadPool(int thread_num = gdefualtnum) : _thread_num(thread_num), _isrunning(false), _sleep_thread_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T> &) = delete;
    void operator=(const ThreadPool<T> &) = delete;

public:
    // ThreadPool(int thread_num = gdefualtnum) : _thread_num(thread_num), _isrunning(false), _sleep_thread_num(0)
    // {
    //     pthread_mutex_init(&_mutex, nullptr);
    //     pthread_cond_init(&_cond, nullptr);
    // }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    void Init()
    {
        ThreadMoudle::func_t func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++)
        {
            std::string threadname = "pthread_" + std::to_string(i + 1);
            _threads.emplace_back(threadname, func);
        }
    }
    void Start()
    {
        _isrunning = true;
        for (auto &thread : _threads)
        {
            thread.start();
        }
    }
    void Stop()
    {
        LockQueue();
        _isrunning = false;
        if (_sleep_thread_num > 0)
            WakeUpAll();
        UnLockQueue();
    }
    void Equeue(const T &in)
    {
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(in);
            if (_sleep_thread_num > 0)
                WakeUp();
        }
        UnLockQueue();
    }
    static ThreadPool<T> *GetInstance()
    {
        if (_tp == nullptr)
        {
            LockGuard lockguard(&_sig_mutex);
            if (_tp == nullptr)
            {
                LOG(INFO, "create threadpool\n");
                _tp = new ThreadPool();
                _tp->Init();
                _tp->Start();
            }
            else
            {
                LOG(INFO, "get threadpool\n");
            }
        }
        return _tp;
    }

private:
    int _thread_num;
    int _sleep_thread_num;
    bool _isrunning;
    std::vector<ThreadMoudle::Thread> _threads;
    std::queue<T> _task_queue;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

template <typename T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;
template <typename T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;